package com.example.demo.Service;

import com.example.demo.UserInfo;
import com.example.demo.dao.UserInfoDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * author 陈伯瑞
 * date 2020/5/17 0017 19:53
 * version 1.0
 **/
@Service
public class userInfoService implements UserDetailsService {
    /**
     *
     */
    @Resource
    UserInfoDao userInfoDao;
    private Logger logger = LoggerFactory.getLogger(getClass());
    public UserInfo loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("用户的用户名: {}", username);
        try {
            UserInfo user = userInfoDao.getOne(username);
            logger.info("用户的用户名: {}", user.getPassword());
            logger.info("用户的用户名: {}", user.getRole());
            if (user == null) {
                throw new UsernameNotFoundException("用户名不存在");
            }
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @Transactional
    public UserInfo create(String name,String password) {
        UserInfo user = new UserInfo();
        user.setUsername(name);
        user.setPassword(password);
        if (userInfoDao.existsById(name))
             throw  new RuntimeException("已存在用户");
        userInfoDao.save(user);
        return  user;
    }
    public boolean login (String name,String password) {
        UserInfo user = new UserInfo();
        user.setUsername(name);
        user.setPassword(password);

        if ( userInfoDao.getOne(name).equals(user))
              return  true;
      return false;
    }
    public UserInfo find(String name){
        return  userInfoDao.getOne(name);
    }
}
